from flask import Blueprint, request

from src.api.https import SUCCESS, fail_api, success_api
from src.utils.check_require import login_required
from src.utils.info_tool import getmessage
from src.utils.type_tool import TypeTool

types_api = Blueprint('types_api', __name__, url_prefix='/api/types')

typeTool = TypeTool()

# 新增标签
@types_api.post("/add")
@login_required
def add():
    global typeTool
    #获取请求内容
    getmessage(request)
    name = request.json.get('name')
    fid = request.json.get('fid')
    print(f"name: {name}, fatherid: {fid}")
    #检查请求内容是否合法
    message = typeTool.check(name, fid)
    if message != SUCCESS:
        return fail_api(message)
    #根据父标签名得到父标签id并插入数据库
    typeTool.init(name, fid)
    print("Success!")
    return success_api("添加标签成功！")


# 删除标签
@types_api.delete("/delete/<int:id>")
@login_required
def delete(id):
    global typeTool

    message = typeTool.delete(id)
    if message != SUCCESS:
        print(message)
        return fail_api(message)
    print(f"Deleted tag with id: {id}")
    return success_api("删除标签成功！")


# 批量删除标签
@types_api.delete("/delete")
def batch_delete():
    global typeTool

    ids = request.json.get('ids')
    if not ids:
        return fail_api("请提供要删除的标签ID列表！")

    for tag_id in ids:
        if not typeTool.exists(tag_id):
            return fail_api(f"标签ID {tag_id} 不存在！")
        typeTool.delete(tag_id)

    print(f"Batch deleted tags with ids: {ids}")
    return success_api("批量删除标签成功！")


# 编辑标签
@types_api.put("/edit/<int:id>")
@login_required
def edit(id):
    global typeTool

    typename = request.json.get('name')
    fatherid = request.json.get('fid')

    if not typeTool.exists(id):
        return fail_api("标签不存在！")

    check_msg = typeTool.check(typename, fatherid)
    if check_msg != SUCCESS:
        return fail_api(check_msg)

    typeTool.update(id, typename, fatherid)
    print(f"Edited tag with id: {id}, name: {typename}, fatherid: {fatherid}")
    return success_api("编辑标签成功！")


# 获取标签详情
@types_api.get("/detail/<int:id>")
@login_required
def detail(id):
    global typeTool

    tag_info = typeTool.get(id)
    if not tag_info:
        return fail_api("标签不存在！")

    print(f"Fetched details for tag with id: {id}")
    return success_api(data=tag_info)


# 获取标签列表
@types_api.get("/list")
@login_required
def list_tags():
    global typeTool

    tags = typeTool.list()
    print(f"Fetched all tags, count: {len(tags)}")
    return success_api(data={"tagsList":tags})
